package day19;

import java.io.IOException;
import java.io.Reader;


/**
 * 理解了BufferedReader的原理后，可以自定义一个自己缓冲流对象
 * 然后主要去实现readLine()方法
 * @author wangbiao
 *
 */
public class CustomBufferedReader extends Reader{

	private Reader reader;
	
	
	public CustomBufferedReader(Reader reader) {
		this.reader = reader;
	}


	public String readLine() throws IOException {
		if (null == reader) {
			throw new IOException("读取流为空,读取失败！");
		}
		StringBuilder sb = new StringBuilder();
		int ch = 0;
		while ((ch = reader.read()) != -1) {
			if (ch == '\r') {
				continue;
			}
			if (ch == '\n') {
				return sb.toString();
			}
			sb.append((char)ch);
		}
		if (sb.length() > 0) {
			return sb.toString();
		}
		return null;
	}
	
	/**
	 * 关闭缓冲流，就关闭流对象
	 * @throws IOException
	 */
	public void close() throws IOException {
		if (null == reader) {
			return;
		}
		reader.close();
		reader = null;
	}

	/* 复写Reader的抽象方法
	 * (non-Javadoc)
	 * @see java.io.Reader#read(char[], int, int)
	 */
	@Override
	public int read(char[] cbuf, int off, int len) throws IOException {
		return this.reader.read(cbuf, off, len);
	}
}
